package com.foreveross.action.weixin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.foreveross.SYWebService.vo.ConditionVo;
import com.foreveross.SYWebService.vo.DataVo;
import com.foreveross.common.CommonUtil;
import com.foreveross.common.Constants;
import com.foreveross.common.Exception.ExceptionConstant;
import com.foreveross.common.Exception.SYHttpclientCallException;
import com.foreveross.service.HouseRepairService;
import com.foreveross.service.HouseUserService;
import com.foreveross.service.LogService;
import com.foreveross.util.AuthUtil;
import com.foreveross.util.DateUtil;
import com.foreveross.util.FileUtil;
import com.foreveross.vo.HouseAddress;
import com.foreveross.vo.HouseRepair;
import com.foreveross.vo.HouseUser;
import com.foreveross.vo.HrHouses;
import com.foreveross.vo.HrNewsInfo;
import com.foreveross.vo.Message;
import com.foreveross.vo.Tenement;
import com.foreveross.vo.TenementCost;
import com.foreveross.vo.VisitorCheckIn;
import com.foreveross.vo.common.PageVo;
import com.foreveross.vo.common.ResultVo;
import com.foreveross.weixin.common.Constant;
import com.foreveross.weixin.util.WeixinUtil;

@Controller
@RequestMapping(value = "/weixin/houseRepairController")
public class HouseRepairController {

	private Logger log = Logger.getLogger(HouseRepairController.class);

	@Resource
	private HouseRepairService houseRepairService;

	@Resource
	private HouseUserService houseUserService;

	/**
	 * 获取物业电话
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getTenementPhone")
	public void getTenementPhone(HttpServletRequest request,
			HttpServletResponse response) {
		String weixinId =CommonUtil.getWeixinID(request);
		ResultVo resultVo = new ResultVo();
		try {
			Map<String,Object> map = houseUserService.getTenementPhone(weixinId);
			if(Integer.parseInt(map.get("total").toString()) == 0){
				resultVo.setMessage("获取物业报修列表为空!");
			}
			resultVo.setData(map);
			resultVo.setSuccess(true);
			log.info("获取物业电话成功!");
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("获取物业电话异常！");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 物业报修查看
	 * 
	 * @param request
	 * @param response
	 * @param weixinId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getMyHouseRepair")
	public void getMyHouseRepair(HttpServletRequest request,
			HttpServletResponse response, String weixinId,String currentPage,String pageSize) {
		ResultVo resultVo = new ResultVo();
		try {
			houseRepairService.getMyHouseRepair(
					weixinId, currentPage, pageSize,resultVo);
			log.info("物业报修列表查看成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("物业报修列表查看失败");
			log.error("物业报修列表查看失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	 

	/**
	 * 获取物业地址列表
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/getTenementAddress")
	public void getTenementAddress(HttpServletRequest request,
			HttpServletResponse response,String authenticationStatus,String currentPage,String pageSize) {
		ResultVo resultVo = new ResultVo();
		String weixinId = CommonUtil.getWeixinID(request);
		try {
			int total = (int)houseUserService.getMyHouseUserListCount(weixinId, authenticationStatus);
			PageVo<HouseUser> pageVo = new PageVo<HouseUser>(currentPage,total,pageSize);
			List<HouseUser> list = houseUserService.getMyHouseUserList(weixinId, authenticationStatus, 
					pageVo.getpageIndex(), pageVo.getpageSize());
			pageVo.setData(list);
			resultVo.setSuccess(true);
			if(list!=null && list.size()>0){
				resultVo.setData(pageVo);
			}else{
				resultVo.setData(pageVo);
				resultVo.setMessage("获取物业地址列表为空!");
			}
			
			log.info("获取物业地址列表成功!");
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("获取物业地址列表失败！");
		}
		List list = Arrays.asList("houseRepairs",
				"visitorCheckIns", "tenementCosts", "expresses","messageHouses","newsHouses","optimizedHouses");
		CommonUtil.PrintWriterResultWithJSON(response, resultVo, list);
	}

	/**
	 * 查看报修地址
	 * 
	 * @param request
	 * @param response
	 * @param userId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findHouseUser")
	public void findHouseUser(HttpServletRequest request,
			HttpServletResponse response, String userId) {
		ResultVo resultVo = new ResultVo();
		try {
			HouseUser user = houseUserService.getHouseUser(userId);
			if (user != null) {
				resultVo.setData(user);
			} else {
				resultVo.setData(new ArrayList());
				resultVo.setMessage("获取报修地址为空！");
			}
			resultVo.setSuccess(true);
			 log.info("获取报修地址成功!");
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setSuccess(false);
			resultVo.setMessage("获取报修地址失败！");
		}
		List list = Arrays.asList("houseRepairs",
				"visitorCheckIns", "tenementCosts", "expresses","messageHouses","newsHouses","optimizedHouses");
		CommonUtil.PrintWriterResultWithJSON(response, resultVo, list);
	}
	
	
	/**
	 * 查看各楼盘报修对应的报修类型
	 * 
	 * @param request
	 * @param response
	 * @param houseId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findHouseRepairType")
	public void findHouseRepairType(HttpServletRequest request,HttpServletResponse response, String houseId) {
		ResultVo resultVo = new ResultVo();
		try {
			ConditionVo conditionVo = new ConditionVo();
			conditionVo.setP0("UserRev_GetServiceMainType");
			conditionVo.setP1(houseId);
			Map<String,Object> map  = houseRepairService.synUserRev_GetServiceMainType(conditionVo);
			if(Integer.valueOf(map.get("total").toString())==0){
				resultVo.setMessage("列表信息为空");
			}
			
			resultVo.setSuccess(true);
			resultVo.setData(map);
		}catch(SYHttpclientCallException e){
			resultVo.setSuccess(false);
			resultVo.setMessage(e.getMessage());
		}catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("获取报修类型失败！");
			e.printStackTrace();
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	/**
	 * 添加物业保修
	 * @param request
	 * @param response
	 * @param houseRepair
	 * @param houseUserId
	 * @param houseId
	 * @param mediaId
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/addHouseRepair")
	public void addHouseRepair(HttpServletRequest request,
			HttpServletResponse response, HouseRepair houseRepair,
			String houseUserId,String houseId) {
		ResultVo resultVo = new ResultVo();
		try {
			houseRepair.setStatus(0);
			houseRepair.setCreateTime(new Date());
			houseRepair.setHouseUser(new HouseUser(houseUserId));
			houseRepair.setHrHouses(new HrHouses(houseId));			

			houseRepairService.saveOrUpdate(houseRepair, Constants.UPDATE_ADD);
			resultVo.setSuccess(true);	
			resultVo.setData(houseRepair.getId());
			log.error("物业报修" + Constants.UPDATE_ADD + "成功!");
		}catch (SYHttpclientCallException e) {
			resultVo.setSuccess(false);
			resultVo.setMessage(e.getMessage());
		}catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("物业报修 " + Constants.UPDATE_ADD + "失败");
			log.error("物业报修" + Constants.UPDATE_ADD + "失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = "/getMediaAndUploadImg")
	public void getMediaAndUploadImg(HttpServletRequest request,
			HttpServletResponse response,String houseRepairId,
			String houseId,String houseUserId,String mediaId) {
		ResultVo resultVo = new ResultVo();
		try {
			String url = null;
			//处理上传图片
			if(mediaId != null && !"".equals(mediaId)){
				String [] mediaIds = mediaId.split(",");
				for(String mId : mediaIds){
					String fileUrl = WeixinUtil.getMedia(Constant.accessToken.getAccess_token(), mId, 
							CommonUtil.getRealPath(request), FileUtil.fileRoot+"winxinImage/");
					//为了确保异步返回
					int i = 0;
					while(i<10 && fileUrl == null){
						i++;
						Thread.sleep(2000);
					}
					if(url == null) url = fileUrl;
					else url = url +","+fileUrl;
				}
				log.info("上传图片mediaId"+mediaId+"成功");
			}
			
			HouseRepair houseRepair = (HouseRepair)houseRepairService.findObject(HouseRepair.class, houseRepairId);
			houseRepair.setUrl(url);
			// 向思源接口传送报修数据
			DataVo dataVo = houseRepairService.synHouseRepair(houseRepair, houseId ,houseUserId, request);
			System.out.println("eventID:"+dataVo.get_eventID() +"  |Detail:"+dataVo.get_Detail()+"  |InfoKey :"+dataVo.get_InfoKey());
			int i = 0;
			while(i<10 && dataVo == null){
				i++;
				System.out.println(i);
				Thread.sleep(2000);
			}
			//设置 eventID
			houseRepair.setRepairNo(dataVo.get_eventID());
			houseRepairService.saveOrUpdate(houseRepair, Constants.UPDATE_EDIT);
			resultVo.setSuccess(true);			
			log.error("物业报修 图片下载并传思源成功!");
		}catch (SYHttpclientCallException e) {
			resultVo.setSuccess(false);
			resultVo.setMessage(e.getMessage());
		}catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("物业报修 图片下载并传思源失败");
			log.error("物业报修 图片下载并传思源失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
	
	/**
	 * 查看详细报修进度
	 * 
	 * @param request
	 * @param response
	 * @param eventId  思源接口添加报事成功，返回的报事ID _eventID
	 * @param orgId 楼盘项目ID
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/findHouseRepairDetail")
	public void findHouseRepairDetail(HttpServletRequest request,HttpServletResponse response, String eventId, String orgId) {
		ResultVo resultVo = new ResultVo();
		try {
			ConditionVo conditionVo = new ConditionVo();
			conditionVo.setP0("User_GetServiceDetail");
			conditionVo.setP1(eventId);
			conditionVo.setP2(orgId);
			List<DataVo> dataVoList = houseRepairService.synUser_GetServiceDetail(conditionVo);
			resultVo.setData(dataVoList);
			resultVo.setSuccess(true);
		}catch(SYHttpclientCallException e){
			resultVo.setSuccess(false);
			resultVo.setMessage(e.getMessage());
		}catch (Exception e) {
			e.printStackTrace();
			resultVo.setMessage("查看详细报修进度失败！");
		}
		
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 物业地址修改添加
	 * 
	 * @param request
	 * @param response
	 * @param express
	 * @param updateType
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/saveOrUpdateHouseAddress")
	public void saveOrUpdateHouseAddress(HttpServletRequest request,
			HttpServletResponse response, HouseAddress HouseAddress,
			String updateType) {
		ResultVo resultVo = new ResultVo();
		try {
			String weixinId =CommonUtil.getWeixinID(request);
			HouseAddress.setName(houseUserService.getWexinUserName(weixinId));
			houseRepairService.saveOrUpdate(HouseAddress, updateType);
			resultVo.setSuccess(true);
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("物业地址 " + Constants.UPDATE_ADD + "失败");
			log.error("物业地址" + Constants.UPDATE_ADD + "失败!", e);
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}

	/**
	 * 物业报修删除
	 * 
	 * @param request
	 * @param response
	 * @param ids
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/deleteHouseRepair")
	public void deleteHouseRepair(HttpServletRequest request,
			HttpServletResponse response, String id) {
		ResultVo resultVo = new ResultVo();
		try {
			houseRepairService.deleteObjec("HouseRepair", id);
			resultVo.setSuccess(true);
			log.info("物业报修 删除成功!");
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("物业报修 删除失败");
			log.info("物业报修 删除失败!");
			e.printStackTrace();
		}

		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);
	}
}
